package com.skyworth.web.order.repository;

import com.skyworth.web.order.domain.OrderModel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

import static ognl.OgnlOps.in;

/**
 * Created by skyworth on 2016/6/23.
 */
public interface OrderRepository extends PagingAndSortingRepository<OrderModel, Long> {
    /**
     * 用户的订单
     * @param userId
     * @param pageable
     * @return
     */
    Page<OrderModel> queryByUserId(String userId,Pageable pageable);

    Page<OrderModel> queryByStoreId(long storeId, Pageable pageable);
    
    @Query(value = "SELECT * FROM ff_order WHERE state=0 AND user_id=?1 ORDER BY created_time DESC LIMIT 0,1",nativeQuery = true)
    OrderModel getLastByUserId(String userId);
    @Query(value = "SELECT * FROM ff_order WHERE state=0 AND user_id=?2 AND store_id=?1 ORDER BY created_time DESC LIMIT 0,1",nativeQuery = true)
    OrderModel getLastForUser(long storeId,String userId);
    @Query(value = "SELECT * FROM ff_order WHERE state = 0 AND table_id=?1 ORDER BY created_time DESC LIMIT 0,1",nativeQuery = true)
    OrderModel getLastByTableId(long tableId);
    @Modifying
    @Query("update OrderModel m set m.state =1 where m.state=0 and m.userId = ?1")
    void updateOrderState(String userId);

    @Modifying
    @Query("update OrderModel m set m.state =0,m.tableId = ?1 where m.state=3 and m.userId = ?2")
    void updateOrderCart(long tableId,String userId);

    @Modifying
    @Query("update OrderModel m set m.state =7 where m.state=3 and m.userId = ?1")
    void deleteOrderCart(String userId);


    Page<OrderModel> getOrderListByStoreIdAndUserId(long storeId,String userId,Pageable pageable);

    /**
     *
     * @param id 订单 id
     * @param state 订单state
     */
    @Modifying
    @Query("update OrderModel m set m.state=?2 where m.id=?1")
    void setOrderState(Long id, int state);


   @Query("select om from OrderModel om where om.storeId=?1 and om.state in (0,2) ORDER BY om.createdTime DESC")
//    @Query(value = "select ff_order.*,ff_table.name as tableName from ff_order inner join ff_table on ff_order.table_id = ff_table.id where ff_order.store_id=?1 and ff_order.state in (0,2)",nativeQuery = true)
    List<OrderModel> findOngoingOrders(Long storeId);

}
